<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        let arr = [5, 1, 3, 7, 9, 1, 4, 8, 4, 5, 6, 114, 24, 8, 54, 84, 6, 456, 4, 79, 54, 78, 79, 7, 89, 98, 4]

        function mergeSort(arr) {
            return arr = mergeSortRec(arr);
        }

        function mergeSortRec(arr) {
            if (arr.length === 1) {
                return arr;
            }

            let mid = Math.floor(arr.length / 2);
            let left = arr.slice(0, mid);
            let right = arr.slice(mid, arr.length);

            return merge(mergeSortRec(left), mergeSortRec(right));
        }

        function merge(left, right) {
            let result = [],
                il = 0,
                ir = 0;

            while (il < left.length && ir < right.length) {
                if (left[il] < right[ir]) {
                    result.push(left[il++]);
                } else {
                    result.push(right[ir++]);
                }
            }

            while (il < left.length) {
                result.push(left[il++]);
            }

            while (ir < right.length) {
                result.push(right[ir++]);
            }
            
            return result;
        }


        console.log(mergeSort(arr));
    </script>
</body>

</html>